package com.martin.lib_base.utils


import android.content.Context
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.target.Target
import com.bumptech.glide.request.transition.Transition
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.martin.lib_base.cache.ImageCacheModel
import com.martin.lib_base.impl.GlideEngine
import com.martin.lib_base.ktx.getActivity
import com.martin.lib_base.ktx.loge
import dev.utils.app.MediaStoreUtils
import dev.utils.app.UriUtils
import dev.utils.app.image.ImageUtils
import dev.utils.common.DateUtils
import dev.utils.common.FileUtils
import kotlinx.coroutines.flow.flow
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine


/**
 * @author：Houge
 * @date：2021/12/10 20:05
 */
object MediaUtil {

    //==========图片选择===========//
    fun pickImage(
        context: Context,
        //最多选择数
        maxNum: Int = 9,
        //是否有拍照按钮
        isCamera: Boolean = true,
        callBack: (ArrayList<LocalMedia>) -> Unit
    ) {
        // 预览图片、视频、音频
        PictureSelector.create(context.getActivity())
            .openGallery(SelectMimeType.ofImage())
            .setImageEngine(GlideEngine.createGlideEngine())
            .setMaxSelectNum(maxNum)
            .isDisplayCamera(isCamera)
            .forResult(object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: ArrayList<LocalMedia>?) {
                    result?.let(callBack)
                }

                override fun onCancel() {
                    loge("选择图片 onCancel")
                }
            })
    }

    fun takeImage(
        context: Context,
        callBack: (ArrayList<LocalMedia>) -> Unit
    ) {
        // 预览图片、视频、音频
        PictureSelector.create(context.getActivity())
            .openCamera(SelectMimeType.ofImage())
            .forResult(object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: ArrayList<LocalMedia>?) {
                    result?.let(callBack)
                }

                override fun onCancel() {
                    loge("拍摄图片 onCancel")
                }
            })
    }

    /**
     * 选择视频
     */
    fun pickVideo(
        context: Context,
        //最多选择数
        maxNum: Int = 1,
        //是否有拍照按钮
        isCamera: Boolean = true,
        callBack: (ArrayList<LocalMedia>) -> Unit
    ) {
        PictureSelector.create(context.getActivity())
            .openGallery(SelectMimeType.ofVideo())
            .setImageEngine(GlideEngine.createGlideEngine())
            .setMaxSelectNum(maxNum)
            .isDisplayCamera(isCamera)
            .forResult(object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: ArrayList<LocalMedia>?) {
                    result?.let(callBack)
                }

                override fun onCancel() {
                    loge("拍摄图片 onCancel")
                }
            })
    }

    /**
     * 获取图片drawable
     * 需要确保加载正常
     */
    fun getDrawableFlow(context: Context, resource: Any) = flow {
        emit(suspendCoroutine {
            val target: Target<Drawable> = object : CustomTarget<Drawable>() {
                override fun onResourceReady(
                    resource: Drawable,
                    transition: Transition<in Drawable>?
                ) {
                    it.resume(resource)
                }

                override fun onLoadCleared(placeholder: Drawable?) {
                }
            }
            Glide.with(context)
                .load(resource)
                .into(target)
        })
    }

    /**
     * 保存图片
     */
    fun saveBitmap(
        bitmap: Bitmap,
        savePath: String = ImageCacheModel.folderPath() + "Material${DateUtils.getCurrentTimeMillis()}.png",
        insert: Boolean = false,
        callBack: (String) -> Unit = {}
    ) {
        val saveFile = FileUtils.saveFile(
            savePath,
            ImageUtils.bitmapToByte(bitmap)
        )
        if (insert) {
            val insertImage = MediaStoreUtils.insertImage(
                MediaStoreUtils.createImageUri(),
                UriUtils.getUriForPath(savePath)
            )
        }
        callBack(savePath)
    }

}
